# coding:utf-8
from datetime import datetime, timedelta
import json
import struct
import pymongo
from pymongo import MongoReplicaSetClient
from pymongo import MongoClient
import pymysql
mysqldb_conn = pymysql.connect(host='172.17.32.141',user = "root",passwd = "Figol123",db = "envvibrationmonitorsystem_letukeji")

mongo_client_cluster=pymongo.MongoClient('mongodb://172.17.32.139:30000,172.17.32.140:30000,172.17.32.141:30000')
col_StatisticsEvent24Hours=mongo_client_cluster["vibration_result"]["StatisticsEvent24Hours"]
col_StatisticsEvent30Days=mongo_client_cluster["vibration_result"]["StatisticsEvent30Days"]
col_StatisticsEvent7Days=mongo_client_cluster["vibration_result"]["StatisticsEvent7Days"]

col_event=mongo_client_cluster["vibration_result"]["event"]
col_event_data=mongo_client_cluster["vibration_result"]["event_data"]
col_vibration_leve=mongo_client_cluster["vibration"]

col_Tantile24Hours=mongo_client_cluster["vibration_result"]["Tantile24Hours"]
col_Tantile7Days=mongo_client_cluster["vibration_result"]["Tantile7Days"]
col_Tantile30Days=mongo_client_cluster["vibration_result"]["Tantile30Days"]

#mongo_client_cluster = pymongo.MongoClient('mongodb://172.24.138.161:30000,172.24.138.162:30000,172.24.138.163:30000')
col_event_data_mqtt = mongo_client_cluster["vibration_result_mqtt"]["event_data_mqtt"]
col_event_mqtt = mongo_client_cluster["vibration_result_mqtt"]["event_mqtt"]
col_level_data_mqtt = mongo_client_cluster["vibration_result_mqtt"]["level_data_mqtt"]

#获取需要计算的传感器编号,包括旧编号以及新编号
def getSensorIDs():
    SensorIDs=[]
    mysqldb_conn.commit()
    mysqldb_vibration_cur = mysqldb_conn.cursor()
    mysqldb_conn.ping(reconnect=True)
    #查询采集器ID
    collectors_list = []
    collectorsID_list = []
    sql="select distinct id, collectors_id from cms_collectors"
    mysqldb_vibration_cur.execute(sql)
    #print(sql)
    for row in mysqldb_vibration_cur.fetchall():
        collectorsID_list.append(row[0])
        collectors_list.append( {"id":row[0], "collectors_id":row[1]} )
        #print(row)
        
    #依据采集器ID查询传感器
    sensor_list = []
    sql="select distinct id, sensor_id, sensitivity, collectors_id, channel_id from cms_sensor WHERE collectors_id in ({})".format( ','.join(["%d" % item for item in collectorsID_list]) )
    mysqldb_vibration_cur.execute(sql)
    #print(sql)
    for row in mysqldb_vibration_cur.fetchall():
        sensor_list.append( {"id":row[0], "sensor_id":row[1], "sensitivity":row[2], "collectors_id":row[3], "channel_id":row[4]} )
        #print(row)
    
    #关闭游标        
    mysqldb_vibration_cur.close()
    
    #整合传感器ID
    mqtt_flag=[]
    
    config=""
    with open('../../../service_config_new.json', 'r') as f:
        config = f.read()
    service_config = json.loads(config)
    GateWayList=service_config["GateWayList"]   
    mqtt_flag_list = []
    for item_GateWay in GateWayList:
        if item_GateWay['mqtt_flag'] != 0:
            mqtt_flag_list.append(item_GateWay['GateWayID'])
    
    for i in range( len(sensor_list) ):
        for j in range( len(collectors_list) ):
            if str( collectors_list[j]['id'] ) == sensor_list[i]['collectors_id']:
                #collectorsIDs.append( sensor_list[i]['sensor_id'] )
                temp_collectorsID = collectors_list[j]['collectors_id'].split('_')
                #collectorsIDs_old.append( temp_collectorsID[-1] + "_" + sensor_list[i]['channel_id'] )
                if temp_collectorsID[-1] in mqtt_flag_list:
                    mqtt_flag=1
                else:
                    mqtt_flag=1
                SensorIDs.append( {"old_SensorID":temp_collectorsID[-1] + "_" + sensor_list[i]['channel_id'],\
                                  "new_SensorID":sensor_list[i]['sensor_id'],\
                                  "mqtt_flag":mqtt_flag} )
                 
    return SensorIDs

#计算分位置
#输入参数 旧传感器编号：sensorID，实时振级数据表名：vibration_leve_co_name, 开始时间startTime_str，结束时间：endTime_str
def tantileCount(sensorID, vibration_leve_co_name, startTime_str, endTime_str, mqtt_flag):
    resultList=[]
    sampleList=[]
    if mqtt_flag != 0:
        vibration_leve_data=col_level_data_mqtt.find({"sensorID":sensorID,"samples_time":{"$gte":startTime_str,"$lte":endTime_str}})    
        for item_2 in vibration_leve_data:
            sampleList += item_2['vibration_level']
        vibration_leve_data.close()
    else:
        vibration_leve_data=col_vibration_leve[vibration_leve_co_name].find({"samples_time":{"$gte":startTime_str,"$lte":endTime_str}})       
        for item_2 in vibration_leve_data:
            sampleList.append(item_2['vibration_leve'])
        vibration_leve_data.close()
    sampleListLength=len(sampleList)
    sampleList.sort(reverse=True)
    resultNumber = int( 0.01*sampleListLength )
    if resultNumber < sampleListLength and resultNumber >= 0:
        resultList.append( sampleList[resultNumber] )
    else:
        resultList.append( 0 )
        
    resultNumber = int( 0.05*sampleListLength )
    if resultNumber < sampleListLength and resultNumber >= 0:
        resultList.append( sampleList[resultNumber] )
    else:
        resultList.append( 0 )
        
    resultNumber = int( 0.1*sampleListLength )
    if resultNumber < sampleListLength and resultNumber >= 0:
        resultList.append( sampleList[resultNumber] )
    else:
        resultList.append( 0 )
    
    resultNumber = int( 0.2*sampleListLength )
    if resultNumber < sampleListLength and resultNumber >= 0:
        resultList.append( sampleList[resultNumber] )
    else:
        resultList.append( 0 )
        
    resultNumber = int( 0.3*sampleListLength )
    if resultNumber < sampleListLength and resultNumber >= 0:
        resultList.append( sampleList[resultNumber] )
    else:
        resultList.append( 0 )
        
    resultNumber = int( 0.4*sampleListLength )
    if resultNumber < sampleListLength and resultNumber >= 0:
        resultList.append( sampleList[resultNumber] )
    else:
        resultList.append( 0 )
        
    resultNumber = int( 0.5*sampleListLength )
    if resultNumber < sampleListLength and resultNumber >= 0:
        resultList.append( sampleList[resultNumber] )
    else:
        resultList.append( 0 )
    return resultList

#统计近24小时事件数
def statisticsEvent24Hours(SensorID):
    print("统计近24小时事件数:" + SensorID["old_SensorID"])
    sensorID = SensorID["new_SensorID"]
    sensorID_old = SensorID["old_SensorID"]
    current_tiem = datetime.now().replace( microsecond=0,second=0,minute=0)
    current_tiem_str = current_tiem.strftime("%Y-%m-%d %H:%M:%S.%f")[0:19]    
    
    #is_exist_flag=col_StatisticsEvent24Hours.find({"sensorID":sensorID, "old_SensorID":sensorID_old, "count_time":current_tiem_str}).count()
    is_exist_flag=col_StatisticsEvent24Hours.count_documents({"sensorID":sensorID, "old_SensorID":sensorID_old, "count_time":current_tiem_str})
    if is_exist_flag < 1:
        EndTimeList=[]
        BeginTimeList=[]
        peakLimitEvent=[]
        vibrationLimit1Event=[]
        vibrationLimit2Event=[]
        print(current_tiem)
        for i in range(24):
            countTimeEnd=current_tiem + timedelta( hours = (0-i) )
            countTimeEnd_str=countTimeEnd.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
            countTimeBegin=current_tiem + timedelta(hours = (0-i-1) )
            countTimeBegin_str=countTimeBegin.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
            EndTimeList.append(countTimeEnd_str)
            #BeginTimeList.append(countTimeBegin_str)
            if SensorID['mqtt_flag'] != 0:#== '01E4FA37_01' or sensorID_old == '01E4FA39_01' or sensorID_old == '01E4FA37_03':
                #peakLimitEvent.append( col_event_mqtt.find({"sensorID":sensorID_old,"eventType":1,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() )
                #vibrationLimit1Event.append( col_event_mqtt.find({"sensorID":sensorID_old,"eventType":2,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() )
                #vibrationLimit2Event.append( col_event_mqtt.find({"sensorID":sensorID_old,"eventType":3,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() )
                
                peakLimitEvent.append( col_event_mqtt.count_documents({"sensorID":sensorID_old,"eventType":1,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}) )
                vibrationLimit1Event.append( col_event_mqtt.count_documents({"sensorID":sensorID_old,"eventType":2,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}) )
                vibrationLimit2Event.append( col_event_mqtt.count_documents({"sensorID":sensorID_old,"eventType":3,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}) )
                BeginTimeList.append(countTimeBegin_str[11:16])
            else:
                #peakLimitEvent.append( col_event.find({"sensorID":sensorID_old,"eventType":1,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() )
                #vibrationLimit1Event.append( col_event.find({"sensorID":sensorID_old,"eventType":2,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() )
                #vibrationLimit2Event.append( col_event.find({"sensorID":sensorID_old,"eventType":3,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() )
                
                peakLimitEvent.append( col_event.count_documents({"sensorID":sensorID_old,"eventType":1,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}) )
                vibrationLimit1Event.append( col_event.count_documents({"sensorID":sensorID_old,"eventType":2,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}) )
                vibrationLimit2Event.append( col_event.count_documents({"sensorID":sensorID_old,"eventType":3,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}) )
                BeginTimeList.append(countTimeBegin_str[11:16])
        EndTimeList.reverse()
        BeginTimeList.reverse()
        peakLimitEvent.reverse()
        vibrationLimit1Event.reverse()
        vibrationLimit2Event.reverse()
        item1={"sensorID":sensorID,\
                 "old_SensorID":sensorID_old,\
                 "count_time":current_tiem_str,\
                 "EndTimeList":EndTimeList,\
                 "BeginTimeList":BeginTimeList,\
                 "peakLimitEvent":peakLimitEvent,\
                 "vibrationLimit1Event":vibrationLimit1Event,\
                 "vibrationLimit2Event":vibrationLimit2Event}
        print(item1)
        col_StatisticsEvent24Hours.insert_one(item1)
        
#统计近30天事件数
def statisticsEvent30Days(SensorID):
    print("统计近30天事件数:" + SensorID["old_SensorID"])
    sensorID = SensorID["new_SensorID"]
    sensorID_old = SensorID["old_SensorID"]
    
    current_tiem = datetime.now().replace( microsecond=0,second=0,minute=0,hour=0)
    current_tiem_str = current_tiem.strftime("%Y-%m-%d %H:%M:%S.%f")[0:19]
    
    #is_exist_flag=col_StatisticsEvent30Days.find({"sensorID":sensorID, "old_SensorID":sensorID_old, "count_time":current_tiem_str}).count()
    is_exist_flag=col_StatisticsEvent30Days.count_documents({"sensorID":sensorID, "old_SensorID":sensorID_old, "count_time":current_tiem_str})
    if is_exist_flag < 1:
        EndTimeList=[]
        BeginTimeList=[]
        peakLimitEvent=[]
        vibrationLimit1Event=[]
        vibrationLimit2Event=[]
        #print(current_tiem)
        for i in range(30):
            countTimeEnd=current_tiem + timedelta( days = (0-i) )
            countTimeEnd_str=countTimeEnd.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
            countTimeBegin=current_tiem + timedelta(days = (0-i-1) )
            countTimeBegin_str=countTimeBegin.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
            EndTimeList.append(countTimeEnd_str[0:10])
            BeginTimeList.append(countTimeBegin_str[0:10])
            if SensorID['mqtt_flag'] != 0 :#sensorID_old == '01E4FA37_01' or sensorID_old == '01E4FA39_01' or sensorID_old == '01E4FA37_03':
                #peakLimitEvent.append( col_event_mqtt.find({"sensorID":sensorID_old,"eventType":1,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() )
                #peakLimitEvent.append( col_event_mqtt.find({"sensorID":sensorID_old,"eventType":1,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() )
                #vibrationLimit1Event.append( col_event_mqtt.find({"sensorID":sensorID_old,"eventType":2,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() )
                #vibrationLimit2Event.append( col_event_mqtt.find({"sensorID":sensorID_old,"eventType":3,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() )
                
                peakLimitEvent.append( col_event_mqtt.count_documents({"sensorID":sensorID_old,"eventType":1,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}) )
                #peakLimitEvent.append( col_event_mqtt.count_documents({"sensorID":sensorID_old,"eventType":1,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}) )
                vibrationLimit1Event.append( col_event_mqtt.count_documents({"sensorID":sensorID_old,"eventType":2,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}) )
                vibrationLimit2Event.append( col_event_mqtt.count_documents({"sensorID":sensorID_old,"eventType":3,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}) )
            else:
                #peakLimitEvent.append( col_event.find({"sensorID":sensorID_old,"eventType":1,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() )
                #vibrationLimit1Event.append( col_event.find({"sensorID":sensorID_old,"eventType":2,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() )
                #vibrationLimit2Event.append( col_event.find({"sensorID":sensorID_old,"eventType":3,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() )
                
                peakLimitEvent.append( col_event.count_documents({"sensorID":sensorID_old,"eventType":1,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}) )
                vibrationLimit1Event.append( col_event.count_documents({"sensorID":sensorID_old,"eventType":2,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}) )
                vibrationLimit2Event.append( col_event.count_documents({"sensorID":sensorID_old,"eventType":3,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}) )
                
        EndTimeList.reverse()
        BeginTimeList.reverse()
        peakLimitEvent.reverse()
        vibrationLimit1Event.reverse()
        vibrationLimit2Event.reverse()
        item1={"sensorID":sensorID,\
                 "old_SensorID":sensorID_old,\
                 "count_time":current_tiem_str,\
                 "EndTimeList":EndTimeList,\
                 "BeginTimeList":BeginTimeList,\
                 "peakLimitEvent":peakLimitEvent,\
                 "vibrationLimit1Event":vibrationLimit1Event,\
                 "vibrationLimit2Event":vibrationLimit2Event}
        print(item1)
        col_StatisticsEvent30Days.insert_one(item1)
        
#统计近30天事件数
def statisticsEvent7Days(SensorID):
    print("统计近7天事件数:" + SensorID["old_SensorID"])
    sensorID = SensorID["new_SensorID"]
    sensorID_old = SensorID["old_SensorID"]
    
    current_tiem = datetime.now().replace( microsecond=0,second=0,minute=0,hour=0)
    current_tiem_str = current_tiem.strftime("%Y-%m-%d %H:%M:%S.%f")[0:19]
    
    #is_exist_flag=col_StatisticsEvent30Days.find({"sensorID":sensorID, "old_SensorID":sensorID_old, "count_time":current_tiem_str}).count()
    is_exist_flag=col_StatisticsEvent7Days.count_documents({"sensorID":sensorID, "old_SensorID":sensorID_old, "count_time":current_tiem_str})
    if is_exist_flag < 1:
        EndTimeList=[]
        BeginTimeList=[]
        peakLimitEvent=[]
        vibrationLimit1Event=[]
        vibrationLimit2Event=[]
        #print(current_tiem)
        for i in range(7):
            countTimeEnd=current_tiem + timedelta( days = (0-i) )
            countTimeEnd_str=countTimeEnd.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
            countTimeBegin=current_tiem + timedelta(days = (0-i-1) )
            countTimeBegin_str=countTimeBegin.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
            EndTimeList.append(countTimeEnd_str[0:10])
            BeginTimeList.append(countTimeBegin_str[0:10])
            if SensorID['mqtt_flag'] != 0 :#sensorID_old == '01E4FA37_01' or sensorID_old == '01E4FA39_01' or sensorID_old == '01E4FA37_03':
                #peakLimitEvent.append( col_event_mqtt.find({"sensorID":sensorID_old,"eventType":1,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() )
                #peakLimitEvent.append( col_event_mqtt.find({"sensorID":sensorID_old,"eventType":1,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() )
                #vibrationLimit1Event.append( col_event_mqtt.find({"sensorID":sensorID_old,"eventType":2,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() )
                #vibrationLimit2Event.append( col_event_mqtt.find({"sensorID":sensorID_old,"eventType":3,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() )
                
                #peakLimitEvent.append( col_event_mqtt.count_documents({"sensorID":sensorID_old,"eventType":1,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}) )
                peakLimitEvent.append( col_event_mqtt.count_documents({"sensorID":sensorID_old,"eventType":1,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}) )
                vibrationLimit1Event.append( col_event_mqtt.count_documents({"sensorID":sensorID_old,"eventType":2,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}) )
                vibrationLimit2Event.append( col_event_mqtt.count_documents({"sensorID":sensorID_old,"eventType":3,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}) )
            else:
                #peakLimitEvent.append( col_event.find({"sensorID":sensorID_old,"eventType":1,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() )
                #vibrationLimit1Event.append( col_event.find({"sensorID":sensorID_old,"eventType":2,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() )
                #vibrationLimit2Event.append( col_event.find({"sensorID":sensorID_old,"eventType":3,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}).count() )
                
                peakLimitEvent.append( col_event.count_documents({"sensorID":sensorID_old,"eventType":1,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}) )
                vibrationLimit1Event.append( col_event.count_documents({"sensorID":sensorID_old,"eventType":2,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}) )
                vibrationLimit2Event.append( col_event.count_documents({"sensorID":sensorID_old,"eventType":3,"eventStartTime":{"$gte":countTimeBegin_str,"$lt":countTimeEnd_str}}) )
                
        EndTimeList.reverse()
        BeginTimeList.reverse()
        peakLimitEvent.reverse()
        vibrationLimit1Event.reverse()
        vibrationLimit2Event.reverse()
        item1={"sensorID":sensorID,\
                 "old_SensorID":sensorID_old,\
                 "count_time":current_tiem_str,\
                 "EndTimeList":EndTimeList,\
                 "BeginTimeList":BeginTimeList,\
                 "peakLimitEvent":peakLimitEvent,\
                 "vibrationLimit1Event":vibrationLimit1Event,\
                 "vibrationLimit2Event":vibrationLimit2Event}
        print(item1)
        col_StatisticsEvent7Days.insert_one(item1)


def countTantile24Hours(SensorID):
    print("统计近24小时分位值:" + SensorID["old_SensorID"])
    sensorID = SensorID["new_SensorID"]
    sensorID_old = SensorID["old_SensorID"]
    vibration_leve_co_name="vibration_leve_"+sensorID_old
    
    resultList=[]
    
    endTime = datetime.now().replace( microsecond=0,second=0,minute=0)
    current_tiem_str = endTime.strftime("%Y-%m-%d %H:%M:%S.%f")[0:19]
    
    #is_exist_flag=col_Tantile24Hours.find({"sensorID":sensorID, "old_SensorID":sensorID_old, "count_time":current_tiem_str}).count()
    is_exist_flag=col_Tantile24Hours.count_documents({"sensorID":sensorID, "old_SensorID":sensorID_old, "count_time":current_tiem_str})
    
    if is_exist_flag < 1:
        endTime_str=endTime.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
        #print(endTime_str)
        startTime_str=""
        
        tantileList=[]
        startTime=endTime + timedelta( hours = -1 )
        startTime_str=startTime.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
        tantileList.append("近1小时")
        tantileList += tantileCount(sensorID_old, vibration_leve_co_name, startTime_str, endTime_str, SensorID['mqtt_flag'])
        item1={"cycleTime":2, "tantileList":tantileList}
        resultList.append(tantileList)
        
        tantileList=[]
        startTime=endTime + timedelta( hours = -2 )
        startTime_str=startTime.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
        tantileList.append("近2小时")
        tantileList += tantileCount(sensorID_old, vibration_leve_co_name, startTime_str, endTime_str, SensorID['mqtt_flag'])
        item1={"cycleTime":4, "tantileList":tantileList}
        resultList.append(tantileList)
        
        tantileList=[]
        startTime=endTime + timedelta( hours = -4 )
        startTime_str=startTime.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
        tantileList.append("近4小时")
        tantileList += tantileCount(sensorID_old, vibration_leve_co_name, startTime_str, endTime_str, SensorID['mqtt_flag'])
        item1={"cycleTime":8, "tantileList":tantileList}
        resultList.append(tantileList)
        
        tantileList=[]
        startTime=endTime + timedelta( hours = -8 )
        startTime_str=startTime.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
        tantileList.append("近8小时")
        tantileList += tantileCount(sensorID_old, vibration_leve_co_name, startTime_str, endTime_str, SensorID['mqtt_flag'])
        item1={"cycleTime":12, "tantileList":tantileList}
        resultList.append(tantileList)
        
        tantileList=[]
        startTime=endTime + timedelta( hours = -24 )
        startTime_str=startTime.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
        tantileList.append("近24小时")
        tantileList += tantileCount(sensorID_old, vibration_leve_co_name, startTime_str, endTime_str, SensorID['mqtt_flag'])
        item1={"cycleTime":16, "tantileList":tantileList}
        resultList.append(tantileList)
        
        item2 = {"sensorID":sensorID,\
                     "old_SensorID":sensorID_old,\
                     "count_time":current_tiem_str,\
                     "tantileList":resultList,"endTime":endTime_str,"startTime":startTime_str}
        col_Tantile24Hours.insert_one(item2)

def countTantile7Days(SensorID):
    print("统计近7天分位值:" + SensorID["old_SensorID"])
    sensorID = SensorID["new_SensorID"]
    sensorID_old = SensorID["old_SensorID"]
    vibration_leve_co_name="vibration_leve_"+sensorID_old
    
    resultList=[]
    
    endTime = datetime.now().replace( microsecond=0,second=0,minute=0,hour=0)
    current_tiem_str = endTime.strftime("%Y-%m-%d %H:%M:%S.%f")[0:19]
    
    #is_exist_flag=col_Tantile24Hours.find({"sensorID":sensorID, "old_SensorID":sensorID_old, "count_time":current_tiem_str}).count()
    is_exist_flag=col_Tantile7Days.count_documents({"sensorID":sensorID, "old_SensorID":sensorID_old, "count_time":current_tiem_str})
    
    if is_exist_flag < 1:
        endTime_str=endTime.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
        #print(endTime_str)
        startTime_str=""
        
        tantileList=[]
        startTime=endTime + timedelta( days = -7 )
        startTime_str=startTime.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
        tantileList = tantileCount(sensorID_old, vibration_leve_co_name, startTime_str, endTime_str, SensorID['mqtt_flag'])
        resultList.append(tantileList)
        
        item2 = {"sensorID":sensorID,\
                     "old_SensorID":sensorID_old,\
                     "count_time":current_tiem_str,\
                     "tantileList":resultList,"endTime":endTime_str,"startTime":startTime_str}
        col_Tantile7Days.insert_one(item2)
        
def countTantile30Days(SensorID):
    print("统计近30天分位值:" + SensorID["old_SensorID"])
    sensorID = SensorID["new_SensorID"]
    sensorID_old = SensorID["old_SensorID"]
    vibration_leve_co_name="vibration_leve_"+sensorID_old
    
    resultList=[]
    
    endTime = datetime.now().replace( microsecond=0,second=0,minute=0,hour=0)
    current_tiem_str = endTime.strftime("%Y-%m-%d %H:%M:%S.%f")[0:19]
    
    #is_exist_flag=col_Tantile24Hours.find({"sensorID":sensorID, "old_SensorID":sensorID_old, "count_time":current_tiem_str}).count()
    is_exist_flag=col_Tantile30Days.count_documents({"sensorID":sensorID, "old_SensorID":sensorID_old, "count_time":current_tiem_str})
    
    if is_exist_flag < 1:
        endTime_str=endTime.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
        #print(endTime_str)
        startTime_str=""
        
        tantileList=[]
        startTime=endTime + timedelta( days = -30 )
        startTime_str=startTime.strftime("%Y-%m-%d %H:%M:%S.%f")[0:21]
        tantileList = tantileCount(sensorID_old, vibration_leve_co_name, startTime_str, endTime_str, SensorID['mqtt_flag'])
        resultList.append(tantileList)
        
        item2 = {"sensorID":sensorID,\
                     "old_SensorID":sensorID_old,\
                     "count_time":current_tiem_str,\
                     "tantileList":resultList,"endTime":endTime_str,"startTime":startTime_str}
        col_Tantile30Days.insert_one(item2)
        
def jobsFor24Hours(SensorID):
    statisticsEvent24Hours(SensorID)
    countTantile24Hours(SensorID)
    
def jobsForDays(SensorID):
    if ( "00" == datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[11:13] ):
        print(datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[11:13])
        statisticsEvent7Days(SensorID)
        statisticsEvent30Days(SensorID)
        countTantile7Days(SensorID)
        countTantile30Days(SensorID)
    
    
def all_jobs():
    SensorIDs=getSensorIDs()
    print(getSensorIDs())
    for i in range( len(SensorIDs) ):
        print(SensorIDs[i])
        jobsForDays(SensorIDs[i])
        jobsFor24Hours(SensorIDs[i])
        

#整点运行
def main():
    all_jobs()

if __name__ == '__main__':
    main()